<?php

/**
 * Description of DateValidate
 *
 * @author Eman
 */
class Lib_DateValidator extends Zend_Validate_Abstract
{
    const INVALID_DATE = 'dateInvalid';
    const INVALID_DURATION = 'dateDifferenceInvalid';

    protected $_messageTemplates = array(
        self::INVALID_DATE => "'%value%' is not a valid date. It's in the future.",
        self::INVALID_DURATION => "Input duration is not valid."
    );

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if $values are valid dates
     * and forms a valid duration.
     *
     * @param  array $values
     * @return boolean
     */
    public function isValid($value, $context=null)
    {
        $inputDate = $this->format($value);
        $inputDate = array ('year'=> $inputDate[0], 'month'=>$inputDate[1] , 'day'=> $inputDate[2]);
        $date = new Zend_Date($inputDate);

        $currentDate = new Zend_Date();

        
        if($date->isLater($currentDate))
        {
            $this->_setValue($value);
            $this->_error(self::INVALID_DATE);
            return false;

        }

       if ($context['to'])
       {
          $fromDate = $this->format($context['from']);
          $fromDate = array ('year'=> $fromDate[0], 'month'=>$fromDate[1] , 'day'=> $fromDate[2]);
          $from = new Zend_Date($fromDate);

          $toDate = $this->format($context['to']);
          $toDate = array ('year'=> $toDate[0], 'month'=>$toDate[1] , 'day'=> $toDate[2]);
          $to = new Zend_Date($toDate);
           
          if($from->isLater($to))
            {
                $this->_error(self::INVALID_DURATION);
                return false;
            }
       }

        return true;
    }

   /**
    * Reformate the date as an array
    * @param string $date
    * @return array
    */
    public function format ($date)
    {
        return (explode('-', $date));
    
   }
}
